<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>线程安全 | my world | 相信自己，做好自己</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="线程安全">
    <meta name="description" content="线程安全，作何解?
多线程环境中，当涉及到共享数据时候，就要考虑线程安全问题。要进行同步，就是加锁，关键字synchronized 。就是同一时刻只能有一个线程访问共享资源。
举例说明，引用来自http://www.importnew.com/23010.html?replytocom=539047#respond

高并发情况下，使用工具类1234567891011121314151617181">
<meta property="og:type" content="article">
<meta property="og:title" content="线程安全">
<meta property="og:url" content="http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/index.html">
<meta property="og:site_name" content="my world">
<meta property="og:description" content="线程安全，作何解?
多线程环境中，当涉及到共享数据时候，就要考虑线程安全问题。要进行同步，就是加锁，关键字synchronized 。就是同一时刻只能有一个线程访问共享资源。
举例说明，引用来自http://www.importnew.com/23010.html?replytocom=539047#respond

高并发情况下，使用工具类1234567891011121314151617181">
<meta property="og:updated_time" content="2017-02-13T02:29:37.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="线程安全">
<meta name="twitter:description" content="线程安全，作何解?
多线程环境中，当涉及到共享数据时候，就要考虑线程安全问题。要进行同步，就是加锁，关键字synchronized 。就是同一时刻只能有一个线程访问共享资源。
举例说明，引用来自http://www.importnew.com/23010.html?replytocom=539047#respond

高并发情况下，使用工具类1234567891011121314151617181">
    
        <link rel="alternative" href="/atom.xml" title="my world" type="application/atom+xml">
    
    <link rel="shortcut icon" href="/myblog/favicon.ico">
    <link rel="stylesheet" href="/myblog/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/myblog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/myblog/img/head.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">李宁</h5>
          <a href="mailto:13521596672@163.com" title="13521596672@163.com" class="mail">13521596672@163.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/myblog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/myblog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/myblog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/lndream" target="_blank" >
                <i class="icon icon-lg icon-git"></i>
                git
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://weibo.com/lndream" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                微博
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/myblog/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">线程安全</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">线程安全</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-02-07T16:00:00.000Z" itemprop="datePublished" class="page-time">
  2017-02-08
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/myblog/categories/线程/">线程</a></li></ul>

            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#线程安全，作何解"><span class="post-toc-number">1.</span> <span class="post-toc-text">线程安全，作何解?</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#举例说明，引用来自"><span class="post-toc-number">2.</span> <span class="post-toc-text">举例说明，引用来自</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#那么为什么出现这个问题？？"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">那么为什么出现这个问题？？</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#所以正确做法是"><span class="post-toc-number">3.</span> <span class="post-toc-text">所以正确做法是</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#总结"><span class="post-toc-number"></span> <span class="post-toc-text">总结</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#提示"><span class="post-toc-number"></span> <span class="post-toc-text">提示</span></a>
        </nav>
    </aside>
    
<article id="post-线程安全之SimpleDateFormat"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">线程安全</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年02月08日 0:00" datetime="2017-02-07T16:00:00.000Z"  itemprop="datePublished">2017-02-08</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/myblog/categories/线程/">线程</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h3 id="线程安全，作何解"><a href="#线程安全，作何解" class="headerlink" title="线程安全，作何解?"></a>线程安全，作何解?</h3><blockquote>
<p>多线程环境中，当涉及到共享数据时候，就要考虑线程安全问题。要进行同步，就是加锁，关键字synchronized 。就是同一时刻只能有一个线程访问共享资源。</p>
<h3 id="举例说明，引用来自"><a href="#举例说明，引用来自" class="headerlink" title="举例说明，引用来自"></a>举例说明，引用来自</h3><p><a href="http://www.importnew.com/23010.html?replytocom=539047#respond" target="_blank" rel="external">http://www.importnew.com/23010.html?replytocom=539047#respond</a></p>
</blockquote>
<p>高并发情况下，使用工具类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateUtil</span> </span>&#123;</div><div class="line"> </div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="title">DateUtil</span><span class="params">()</span></span>&#123;&#125;</div><div class="line"> </div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> DateFormat DATE_FORMAT = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>);</div><div class="line"> </div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Date <span class="title">parse</span><span class="params">(String date)</span>  <span class="keyword">throws</span> ParseException </span>&#123;</div><div class="line">        <span class="keyword">return</span> DATE_FORMAT.parse(date);</div><div class="line">    &#125;    </div><div class="line"> </div><div class="line">``` </div><div class="line"> 由此而造成异常 </div><div class="line">```java</div><div class="line">java.lang.NumberFormatException: For input string: <span class="string">""</span></div><div class="line">        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:<span class="number">48</span>)</div><div class="line">        at java.lang.Long.parseLong(Long.java:<span class="number">431</span>)</div><div class="line">        at java.lang.Long.parseLong(Long.java:<span class="number">468</span>)</div><div class="line">        at java.text.DigitList.getLong(DigitList.java:<span class="number">177</span>)</div><div class="line">        at java.text.DecimalFormat.parse(DecimalFormat.java:<span class="number">1297</span>)</div><div class="line">        at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:<span class="number">1589</span>)</div><div class="line">        at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:<span class="number">1311</span>)</div><div class="line">        at java.text.DateFormat.parse(DateFormat.java:<span class="number">335</span>)</div><div class="line">        at com.xxxxxxx.core.common.util.DateUtil.parseTimestamp(DateUtil.java:<span class="number">95</span>)</div><div class="line">        at com.xxxxxxx.core.common.util.DateUtil.parse(DateUtil.java:<span class="number">84</span>)</div><div class="line">        at com.xxxxxxx.hbase.generator.LogRowKeyGenerator.generate(LogRowKeyGenerator.java:<span class="number">21</span>)</div><div class="line">        ... <span class="number">22</span> more</div></pre></td></tr></table></figure></p>
<h4 id="那么为什么出现这个问题？？"><a href="#那么为什么出现这个问题？？" class="headerlink" title="那么为什么出现这个问题？？"></a>那么为什么出现这个问题？？</h4><p>查看SimpleDateFormat的源码会发现，最前面的注释<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">* Date formats are not synchronized.</div><div class="line">* It is recommended to create separate format instances for each thread.</div><div class="line">* If multiple threads access a format concurrently, it must be synchronized</div><div class="line">* externally.</div></pre></td></tr></table></figure></p>
<p>翻译过来就是</p>
<blockquote>
<p>日期格式化的类是非同步的，建议为每一个线程创建独立的格式化实例。如果多个线程并发访问同一个格式化实例，就必须在外部添加同步机制</p>
</blockquote>
<p>说明这样做是线程不安全的（把DateFormat DATE_FORMAT = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”) 作为了全局变量，是一个共享资源）。</p>
<h3 id="所以正确做法是"><a href="#所以正确做法是" class="headerlink" title="所以正确做法是"></a>所以正确做法是</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateUtil</span> </span>&#123;</div><div class="line"> </div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="title">DateUtil</span><span class="params">()</span></span>&#123;&#125;</div><div class="line"> </div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Date <span class="title">parse</span><span class="params">(String date)</span>  <span class="keyword">throws</span> ParseException </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>).parse(date);</div><div class="line">    &#125;    </div><div class="line"> </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>把一个非同步 *Date formats are not synchronized的作为全局变量，也就是一个共享资源，没有加上锁，在高并发的情况下，出现意想不到的bug。现在的改法是把其变成非共享的资源，也就是为每一个线程创建独立的格式化实例，这样就不用使用锁来解决了。</p>
<h2 id="提示"><a href="#提示" class="headerlink" title="提示"></a>提示</h2><blockquote>
<ol>
<li><p>时间相关的操作建议使用Java 8新添加的Time包</p>
</li>
<li><p>共享对象时, 基本都会去看看类是不是线程安全的。谷歌guava库, joda-time, jackson这些常用的工具包, 在类的注释上都会标明是不是thread safe</p>
</li>
</ol>
</blockquote>
<!--<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/myblog/tu/sh.png" alt="这里写图片描述" title="">
                </div>
                <div class="image-caption">这里写图片描述</div>
            </figure>–&gt;
-->
        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-02-13T02:29:37.000Z" itemprop="dateUpdated">2017年2月13日 10:29</time>
</span><br>


        如要转载请注明出处：<a href="/myblog/2017/02/08/线程安全之SimpleDateFormat/" target="_blank" rel="external">http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/</a>
    </div>
    <footer>
        <a href="http://lndream.oschina.io/myblog">
            <img src="/myblog/img/head.jpg" alt="李宁">
            李宁
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/myblog/tags/线程安全/">线程安全</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/&title=《线程安全》 — my world&pic=http://lndream.oschina.io/myblog/img/head.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/&title=《线程安全》 — my world&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《线程安全》 — my world&url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/&via=http://lndream.oschina.io/myblog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/myblog/2017/02/20/shiro介绍/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">shiro配置相关</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/myblog/2017/02/07/hello-world/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Hello World</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/myblog/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/myblog/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/lndream" target="_blank">李宁</a></span>
            <span>my world &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/&title=《线程安全》 — my world&pic=http://lndream.oschina.io/myblog/img/head.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/&title=《线程安全》 — my world&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《线程安全》 — my world&url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/&via=http://lndream.oschina.io/myblog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://lndream.oschina.io/myblog/2017/02/08/线程安全之SimpleDateFormat/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/myblog/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/myblog/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/myblog/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
